package com.tedu.springboot2307.controller;

import com.sun.net.httpserver.HttpServer;
import com.tedu.springboot2307.entity.Article;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller//支持注解
public class ArticleController {
    private static File articleDir;
    static {
        articleDir = new File("./articles");
        if(!articleDir.exists()){
            articleDir.mkdirs();
        }
    }

    @RequestMapping("/writeArticle")
    public void writeArticle(HttpServletRequest request, HttpServletResponse response){
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String content = request.getParameter("content");

        if (title==null || title.isEmpty() ||
            author==null || author.isEmpty() ||
            content==null || content.isEmpty()){

            try {
                response.sendRedirect("article_fail.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        File file = new File(articleDir,title+".obj");
        if(file.exists()){
            try {
                response.sendRedirect("article_fail.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        Article article = new Article(title, author, content);

        try (
                FileOutputStream fos = new FileOutputStream(file);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
        ){
            oos.writeObject(article);
            response.sendRedirect("article_success.html");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @RequestMapping("/articleList")
    public void publishArticle(HttpServletRequest request, HttpServletResponse response){
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        File[] files = articleDir.listFiles(f->f.getName().endsWith(".obj"));
    }
}
